package la.bbs558.satoken;

import cn.dev33.satoken.stp.StpInterface;
import la.bbs558.entity.UserRole;
import la.bbs558.entity.enums.RedisKey;
import la.bbs558.service.UserRoleService;
import la.bbs558.util.Objs;
import la.bbs558.util.Strings;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * 自定义权限加载接口实现类
 */
@Component    // 保证此类被 SpringBoot 扫描，完成 Sa-Token 的自定义权限验证扩展
public class StpInterfaceImpl implements StpInterface {

    @Resource
    private UserRoleService userRoleService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        // 本 list 仅做模拟，实际项目中要根据具体业务逻辑来查询权限
        List<String> list = new ArrayList<>();
        list.add("*");
        return list;
    }

    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Override
    @SuppressWarnings("unchecked")
    public List<String> getRoleList(Object loginId, String loginType) {
        String key = RedisKey.USER_ROLE.spaceName(loginId);
        Object rolesObj = redisTemplate.opsForValue().get(key);
        if (Objs.isValid(rolesObj)) {
            return (List<String>) rolesObj;
        }
        Optional<UserRole> userRole = userRoleService.lambdaQuery().eq(UserRole::getUserId, loginId).oneOpt();
        if (!userRole.isPresent()) {
            return Collections.EMPTY_LIST;
        }
        String roleIds = userRole.get().getRoleIds();
        if (Objs.isInvalid(roleIds)) {
            return Collections.EMPTY_LIST;
        }
        List<String> roles = Strings.split(roleIds, ",");
        redisTemplate.opsForValue().set(key, roles, 1, TimeUnit.DAYS);
        return roles;
    }

}

